package com.k2data;

/**
 * Created by lijianing on 17-11-8.
 */
import java.io.IOException;
import java.util.Random;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class ExtractMetadata {
    public static class ExtractMapper
            extends Mapper<Object, Text, Text, NullWritable>{

        private Text word = new Text();

        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            String attrs = value.toString().substring(0, value.toString().indexOf(":"));
            String key1 = attrs.substring(0, attrs.lastIndexOf("|"));
            word.set(key1);
            context.write(word, NullWritable.get());
        }
    }

    public static class ExtractReducer
            extends Reducer<Text, NullWritable,Text,NullWritable> {


        public void reduce(Text key, Iterable<NullWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            context.write(key, NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("mapred.map.child.java.opts",args[3]);
        conf.set("mapred.reduce.child.java.opts",args[4]);
        Job job = Job.getInstance(conf, "metadata tool");
        job.setNumReduceTasks(Integer.valueOf(args[2]));
        job.setJarByClass(ExtractMetadata.class);
        job.setMapperClass(ExtractMapper.class);
        job.setCombinerClass(ExtractReducer.class);
        job.setReducerClass(ExtractReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        FileInputFormat.addInputPaths(job, args[0]);
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
